﻿//+------------------------------------------------------------------+
//|                                                   FZ SCALPER.mq4 |
//|                                                            FZ    |
//|                                                            FZ    |
//+------------------------------------------------------------------+
#property copyright "FZ"
#property link      "FZ"

//-----------------------Risk Parameters-----------------------------+
extern string   t0="Risk Parameters";
extern double   Risk          =0.1;          // Risk percentage per trade (%)
extern double   TP            =0.25;       // Take profit percentage (of balance)
extern double   单量止盈计算基数 = 4000.0;   // Fixed trade amount (USD)

extern string   t2="Trail and Step";
extern int      Tral          =0;          // Trailing stop distance (0=disabled)
extern int      TralStep      =0;          // Trailing step size (if >0, step trailing)
extern int      Step          =50;         // Grid step between orders (points)

extern string   t3="Hedge Settings";
extern int      启动对冲单数=5;         // Number of orders to trigger hedge/Max number of orders in one direction
extern double   启动对冲亏损金额=100.0;    // Loss amount to trigger hedge (account currency)
extern double   对冲倍数=1.0;      // Hedge lot size multiplier
extern bool     CloseAfterHedge=false;    // Close original orders after hedging

extern string   t4="Trading Hour";
extern int      StartTime     =1;          // Trading session start hour
extern int      EndTime       =23;         // Trading session end hour

extern string   t5="MA Parameters";
extern int      BarShift      =0;          // Bar shift for MA calculation
extern int      Tf            =0;          // Timeframe for MA (0=current chart)
extern int      Per           =8;          // MA period
extern int      Shift         =0;          // MA shift
extern int      Metod         =3;          // MA method (0=SMA,1=EMA,2=SMMA,3=LWMA)
extern int      Pric          =0;          // Applied price (0=Close,1=Open,etc)

extern string   t6="Others";
extern int      Slip          =10;         // Maximum slippage allowance
extern int      Magic         =123;        // Unique EA identifier
extern string   Name          ="FZ"; // Order comment text
extern bool     Info          =true;       // Enable on-chart display
#define BUTTON_WIDTH 80
#define BUTTON_HEIGHT 20
#define CLOSE_BUY_BUTTON "CloseBuys"
#define CLOSE_SELL_BUTTON "CloseSells"

//--------------------------------------------------------------------+
int D; // Point multiplier for 5-digit brokers
bool HedgeActive = false; // [HEDGE] Hedge activation flag
double Lot = 0;  // Global declaration

//+------------------------------------------------------------------+
//| Time zone offset calculation function                                             |
//+------------------------------------------------------------------+
int GetLocalTimeOffset()
{
    MqlDateTime gmtTime, serverTime;
    TimeGMT(gmtTime);       // GMT time
    TimeCurrent(serverTime);// server Time
    return (StructToTime(serverTime) - StructToTime(gmtTime));
}


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
{
    // Handle 5/3 digit brokers (adjust point calculations)
    D=1;
    if (Digits==5 || Digits==3) D=10;


// create close buy button
    ObjectCreate(CLOSE_BUY_BUTTON, OBJ_BUTTON, 0, 0, 0);
    ObjectSetInteger(0, CLOSE_BUY_BUTTON, OBJPROP_XDISTANCE, 20);
    ObjectSetInteger(0, CLOSE_BUY_BUTTON, OBJPROP_YDISTANCE, 150);
    ObjectSetInteger(0, CLOSE_BUY_BUTTON, OBJPROP_XSIZE, BUTTON_WIDTH);
    ObjectSetInteger(0, CLOSE_BUY_BUTTON, OBJPROP_YSIZE, BUTTON_HEIGHT);
    ObjectSetString(0, CLOSE_BUY_BUTTON, OBJPROP_TEXT, "Close Buy");
    ObjectSetInteger(0, CLOSE_BUY_BUTTON, OBJPROP_COLOR, clrWhite);
    ObjectSetInteger(0, CLOSE_BUY_BUTTON, OBJPROP_BGCOLOR, clrRed);
    ObjectSetInteger(0, CLOSE_BUY_BUTTON, OBJPROP_CORNER, CORNER_LEFT_LOWER);

    // create close sell button
    ObjectCreate(CLOSE_SELL_BUTTON, OBJ_BUTTON, 0, 0, 0);
    ObjectSetInteger(0, CLOSE_SELL_BUTTON, OBJPROP_XDISTANCE, 20 + BUTTON_WIDTH + 10);
    ObjectSetInteger(0, CLOSE_SELL_BUTTON, OBJPROP_YDISTANCE, 150);
    ObjectSetInteger(0, CLOSE_SELL_BUTTON, OBJPROP_XSIZE, BUTTON_WIDTH);
    ObjectSetInteger(0, CLOSE_SELL_BUTTON, OBJPROP_YSIZE, BUTTON_HEIGHT);
    ObjectSetString(0, CLOSE_SELL_BUTTON, OBJPROP_TEXT, "Close Sell");
    ObjectSetInteger(0, CLOSE_SELL_BUTTON, OBJPROP_COLOR, clrWhite);
    ObjectSetInteger(0, CLOSE_SELL_BUTTON, OBJPROP_BGCOLOR, clrDodgerBlue);
    ObjectSetInteger(0, CLOSE_SELL_BUTTON, OBJPROP_CORNER, CORNER_LEFT_LOWER);

    return(0);
}

//+------------------------------------------------------------------+
//| Main trading logic                                               |
//+------------------------------------------------------------------+
int start()
{
    // 计算基础交易手数
    Lot = NormalizeDouble(单量止盈计算基数/100*Risk/(MarketInfo(Symbol(),MODE_TICKVALUE)*100*D),2);    
    if (Lot<MarketInfo(Symbol(),MODE_MINLOT)) Lot=MarketInfo(Symbol(),MODE_MINLOT);
    if (Lot>=MarketInfo(Symbol(),MODE_MAXLOT)) Lot=MarketInfo(Symbol(),MODE_MAXLOT);

    // 检查对冲条件（无论EnableHedge状态都持续监控）
    CheckHedgeConditions();
    
    // 当对冲激活时停止所有新交易
    if(HedgeActive) 
    {
        if(Info) CSSComent();
        return(0);
    }

    // 显示信息面板
    if(Info) CSSComent();

    // 止盈逻辑
    double ProcM=单量止盈计算基数 * TP / 100;  
    if(Profit(OP_BUY)>=ProcM && ProcM!=0) Closer(Magic,-1);  
    if(Profit(OP_SELL)>=ProcM && ProcM!=0) Closer(Magic,-1); 

    // 网格加仓逻辑
    if(Count(OP_BUY)>0 && Ask+Step*D*Point<=BuyPric() && Count(OP_BUY) < 启动对冲单数 && !HedgeActive)
    {   
        double Lotb=Lot*Count(OP_BUY)+Lot;
        int ticket_buy = OrderSend(Symbol(),OP_BUY,Lotb,Ask,Slip,0,0,Name,Magic,0,Green);
        if(ticket_buy < 0) Print("Buy OrderSend failed. Error:", GetLastError());
    }
    
    if(Count(OP_SELL)>0 && Bid-Step*D*Point>=SellPric() && Count(OP_SELL) < 启动对冲单数 && !HedgeActive)
    {   
        if(HedgeActive) return(0); 
        double Lots=Lot*Count(OP_SELL)+Lot; 
        int ticket_sell = OrderSend(Symbol(),OP_SELL,Lots,Bid,Slip,0,0,Name,Magic,0,Red);
        if(ticket_sell < 0) Print("Sell OrderSend failed. Error:", GetLastError());
    }

    // 移动止损
    if(Count(OP_BUY)==1) Trail(Magic);
    if(Count(OP_SELL)==1) Trail(Magic); 

    // 主交易窗口逻辑
    if (TimeHour(TimeCurrent()) >= StartTime && TimeHour(TimeCurrent()) <= EndTime)
    {
        if(Count(-1)==0 && !HedgeActive)
        {
            if(LastType()!=OP_BUY && Count(OP_BUY) < 启动对冲单数 && 
               iMA(NULL,Tf,Per,Shift,Metod,0,BarShift+1)<iMA(NULL,Tf,Per,Shift,Metod,0,BarShift))
            {
                int ticket_buy_main = OrderSend(Symbol(),OP_BUY,Lot,Ask,Slip,0,0,Name,Magic,0,Green);
                if(ticket_buy_main < 0) Print("Main Buy Error:", GetLastError());
            }
            
            if(LastType()!=OP_SELL && Count(OP_SELL) < 启动对冲单数 && 
               iMA(NULL,Tf,Per,Shift,Metod,0,BarShift+1)>iMA(NULL,Tf,Per,Shift,Metod,0,BarShift))
            {
                int ticket_sell_main = OrderSend(Symbol(),OP_SELL,Lot,Bid,Slip,0,0,Name,Magic,0,Red);
                if(ticket_sell_main < 0) Print("Main Sell Error:", GetLastError());
            }
        }
    }
    return(0);
}

//+------------------------------------------------------------------+
//| ChartEvent handler                                               |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
    if(id == CHARTEVENT_OBJECT_CLICK)
    {
        
        if(sparam == CLOSE_BUY_BUTTON)
        {
            Closer(Magic, OP_BUY);
            Print("Close all buy orders");
        }
        // 处理平空按钮点击
        else if(sparam == CLOSE_SELL_BUTTON)
        {
            Closer(Magic, OP_SELL);
            Print("Close all sell orders");
        }
    }
}


//+------------------------------------------------------------------+
//| [HEDGE] Check hedge triggering conditions                        |
//+------------------------------------------------------------------+
void CheckHedgeConditions()
{
     if (HedgeActive) return;
    bool thresholdReached = (Count(OP_BUY) >= 启动对冲单数 || Count(OP_SELL) >= 启动对冲单数);
    bool lossTriggered = (CalculateDirectionLoss(OP_BUY) >= 启动对冲亏损金额 || 
                        CalculateDirectionLoss(OP_SELL) >= 启动对冲亏损金额);

    if(thresholdReached && lossTriggered)
    {
        int hedgeType = (Count(OP_BUY) >= 启动对冲单数) ? OP_SELL : OP_BUY;
        double hedgeLots = CalculateDirectionLots(hedgeType == OP_BUY ? OP_SELL : OP_BUY);
        ExecuteHedge(hedgeType, hedgeLots);
        HedgeActive = true;
        Print("对冲激活，停止交易");
    }
}
//+------------------------------------------------------------------+
//| [HEDGE] Calculate lots for specific trade direction              |
//+------------------------------------------------------------------+
double CalculateDirectionLots(int direction)
{
    double totalLots = 0.0;
    for(int i=OrdersTotal()-1; i>=0; i--)
    {
        if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
            if(OrderSymbol() == Symbol() && 
               OrderMagicNumber() == Magic &&
               OrderType() == direction)
            {
                totalLots += OrderLots(); 
            }
        }
    }
    return totalLots;
}
//+------------------------------------------------------------------+
//| [HEDGE] Calculate loss for specific trade direction              |
//+------------------------------------------------------------------+
double CalculateDirectionLoss(int direction)
{
    double totalLoss = 0.0;
    for(int i=OrdersTotal()-1; i>=0; i--)
    {
        if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
            if(OrderSymbol() == Symbol() && 
               OrderMagicNumber() == Magic &&
               OrderType() == direction)
            {
                totalLoss += OrderProfit() + OrderSwap() + OrderCommission();
            }
        }
    }
    return MathAbs(totalLoss); // Return positive value
}

//+------------------------------------------------------------------+
//| [HEDGE] Execute hedge order                                      |
//+------------------------------------------------------------------+
void ExecuteHedge(int hedgeType, double hedgeLots)
{
    hedgeLots = NormalizeDouble(hedgeLots * 对冲倍数, 2);
    double price = (hedgeType == OP_BUY) ? Ask : Bid;
    string comment = "[FullHedge] " + Name;
    
    int ticket = OrderSend(Symbol(), hedgeType, hedgeLots, price, Slip, 0, 0, comment, Magic, 0, (hedgeType==OP_BUY)?Green:Red);
    
    if(ticket > 0)
    {
        Print("对Hedge activated. Type:", hedgeType, " Lots：", hedgeLots);
        HedgeActive = true;
    }
    else
    {
        Print("Hedge failed. Error:", GetLastError());
    }
}



//+------------------------------------------------------------------+
//| Count open positions of specified type                          |
//+------------------------------------------------------------------+
int Count(int type)
{
    int count=0;
    for(int i=OrdersTotal()-1;i>=0;i--)
        if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
            if(Symbol()==OrderSymbol() && OrderMagicNumber()==Magic && (type==-1 || OrderType()==type)) 
                count++;
        }
    return(count);
}

//+------------------------------------------------------------------+
//| Trailing stop management                                         |
//+------------------------------------------------------------------+
void Trail(int _key)
{
    for(int i=0; i<OrdersTotal(); i++)
        if (OrderSelect(i,SELECT_BY_POS) && OrderSymbol()==Symbol() && OrderMagicNumber()==_key)
        {
            if(Tral!=0)
            {
                // Buy position trailing logic
                if (OrderType()==OP_BUY && Bid>MathMax(OrderOpenPrice(),OrderStopLoss())+(Tral+TralStep)*D*Point)
                    if (!OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Tral*D*Point,OrderTakeProfit(),0)) {}
                
                // Sell position trailing logic
                if (OrderType()==OP_SELL && ((Ask<MathMin(OrderOpenPrice(),OrderStopLoss())-(Tral+TralStep)*D*Point && 
                    OrderStopLoss()!=0)||(Ask<OrderOpenPrice()-(Tral+TralStep)*D*Point && OrderStopLoss()==0)))
                    if (!OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Tral*D*Point,OrderTakeProfit(),0)) {}
            }
        }
}

//+------------------------------------------------------------------+
//| Close all positions                                              |
//+------------------------------------------------------------------+
// Order closing function
void Closer(int _key, int type)
{
    for(int i=OrdersTotal()-1;i>=0;i--)
    {
        bool selectResult = OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
        if(!selectResult)
        {
            Print("OrderSelect in Closer failed. Error code: ", GetLastError());
            continue;
        }
        
        if(Symbol()==OrderSymbol() && OrderMagicNumber()==Magic)
        {
            if(type != -1 && OrderType() != type) continue;
            bool closeResult = false;
            if(OrderType()==OP_BUY) 
            {
                closeResult = OrderClose(OrderTicket(),OrderLots(),Bid,Slip,0);
            }
            if(OrderType()==OP_SELL) 
            {
                closeResult = OrderClose(OrderTicket(),OrderLots(),Ask,Slip,0);
            }
            
            if(!closeResult)
            {
                Print("OrderClose failed. Error code: ", GetLastError());
            }
        }
    }
}

//+------------------------------------------------------------------+
//| Get latest buy price from order history                          |
//+------------------------------------------------------------------+
// Buy price retrieval function
double BuyPric() 
{
    double oldorderopenprice = 0;
    int oldticketnumber = 0;
    for (int cnt = OrdersTotal() - 1; cnt >= 0; cnt--) 
    {
        if(!OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
        {
            Print("OrderSelect in BuyPric failed. Error code: ", GetLastError());
            continue;
        }
        
        if (OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && OrderType() == OP_BUY) 
        {
            if (OrderTicket() > oldticketnumber) 
            {
                oldorderopenprice = OrderOpenPrice();
                oldticketnumber = OrderTicket();
            }
        }
    }
    return (oldorderopenprice);
}

//+------------------------------------------------------------------+
//| Retrieve latest sell order open price                           |
//+------------------------------------------------------------------+
double SellPric() 
{
    double oldorderopenprice = 0.0;  // Initialize with default value
    int oldticketnumber = 0;         // Track highest ticket number
    
    // Iterate through all orders in reverse chronological order
    for (int cnt = OrdersTotal() - 1; cnt >= 0; cnt--) 
    {
        // Attempt to select order by position
        if(!OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
        {
            Print("OrderSelect failed at index ", cnt, " Error: ", GetLastError());
            continue;  // Skip to next iteration on failure
        }
        
        // Verify matching symbol and magic number
        if(OrderSymbol() != Symbol() || OrderMagicNumber() != Magic) 
            continue;
        
        // Process sell orders only
        if(OrderType() == OP_SELL) 
        {
            int currentTicket = OrderTicket();
            
            // Update price if newer ticket found
            if(currentTicket > oldticketnumber)
            {
                oldorderopenprice = OrderOpenPrice();
                oldticketnumber = currentTicket;
            }
        }
    }
    
    // Post-processing validation
    if(oldorderopenprice == 0.0) 
        Print("Warning: No valid sell orders found");
    
    return oldorderopenprice;
}

//+------------------------------------------------------------------+
//| Calculate total profit for positions                             |
//+------------------------------------------------------------------+
double Profit(int type) 
{
    double Profit = 0;
    for (int cnt = OrdersTotal() - 1; cnt >= 0; cnt--) 
    {
        if(OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES))
        {
            if (OrderMagicNumber()==Magic && (OrderType() == type || type==-1)) 
                Profit += OrderProfit()+OrderSwap()+OrderCommission();
        }
    }
    return (Profit);
}
//+------------------------------------------------------------------+
//| Calculate profit for today's closed orders                       |
//+------------------------------------------------------------------+
double ProfitDey(int type) 
{
    double Profit = 0;
    datetime serverTodayStart = iTime(Symbol(), PERIOD_D1, 0);
    datetime localTodayStart = serverTodayStart + GetLocalTimeOffset();
    for (int cnt = OrdersHistoryTotal() - 1; cnt >= 0; cnt--) 
    {
        if(OrderSelect(cnt, SELECT_BY_POS, MODE_HISTORY))
        {
            if (OrderMagicNumber() == Magic && 
                OrderCloseTime() >= localTodayStart && 
                (OrderType() == type || type == -1))
            {
                Profit += OrderProfit() + OrderSwap() + OrderCommission();
            }
        }
    }
    return (Profit);
}

//+------------------------------------------------------------------+
//| Calculate profit for yesterday's closed orders                   |
//+------------------------------------------------------------------+
double ProfitTuDey(int type) 
{
    double Profit = 0;
    datetime serverYesterdayStart = iTime(Symbol(), PERIOD_D1, 1);
    datetime localYesterdayStart = serverYesterdayStart + GetLocalTimeOffset();
    datetime localTodayStart = localYesterdayStart + 86400; // +24小时
    
    for(int cnt = OrdersHistoryTotal()-1; cnt>=0; cnt--)
    {
        if(OrderSelect(cnt, SELECT_BY_POS, MODE_HISTORY))
        {
            if(OrderMagicNumber()==Magic && 
               OrderCloseTime() >= localYesterdayStart && 
               OrderCloseTime() < localTodayStart && 
               (OrderType() == type || type == -1))
            {
                Profit += OrderProfit()+OrderSwap()+OrderCommission();
            }
        }
    }
    return Profit;
}


//+------------------------------------------------------------------+
//| Calculate weekly profit (current week)                           |
//+------------------------------------------------------------------+
double ProfitWeek(int type) 
{
    double Profit = 0;
    MqlDateTime localTime;
    TimeToStruct(TimeCurrent(), localTime);
    int daysToWeekStart = (localTime.day_of_week + 6) % 7; // 
    datetime weekStart = TimeCurrent() - daysToWeekStart * 86400;
    
    for(int cnt = OrdersHistoryTotal()-1; cnt>=0; cnt--)
    {
        if(OrderSelect(cnt, SELECT_BY_POS, MODE_HISTORY))
        {
            if(OrderMagicNumber()==Magic && 
               OrderCloseTime() >= weekStart && 
               (OrderType() == type || type == -1))
            {
                Profit += OrderProfit()+OrderSwap()+OrderCommission();
            }
        }
    }
    return Profit;
}


//+------------------------------------------------------------------+
//| Calculate monthly profit (current month)                         |
//+------------------------------------------------------------------+
double ProfitMontag(int type) 
{
    double Profit = 0;
    MqlDateTime localTime;
    TimeToStruct(TimeCurrent(), localTime);
    
    MqlDateTime targetDate;
    targetDate.year = localTime.year;
    targetDate.mon = localTime.mon;
    targetDate.day = 1;
    targetDate.hour = 0;
    targetDate.min = 0;
    targetDate.sec = 0;
    datetime monthStart = StructToTime(targetDate); 
    
    for(int cnt = OrdersHistoryTotal()-1; cnt>=0; cnt--)
    {
        if(OrderSelect(cnt, SELECT_BY_POS, MODE_HISTORY))
        {
            if(OrderMagicNumber()==Magic && 
               OrderCloseTime() >= monthStart && 
               (OrderType() == type || type == -1))
            {
                Profit += OrderProfit()+OrderSwap()+OrderCommission();
            }
        }
    }
    return Profit;
}

//+------------------------------------------------------------------+
//| Calculate all-time profit                                         |
//+------------------------------------------------------------------+
double ProfitAllTime(int type) 
{
    double Profit = 0;
    for(int cnt = OrdersHistoryTotal()-1; cnt>=0; cnt--)
    {
        if(OrderSelect(cnt, SELECT_BY_POS, MODE_HISTORY))
        {
            if(OrderMagicNumber()==Magic && (OrderType() == type || type == -1))
            {
                Profit += OrderProfit()+OrderSwap()+OrderCommission();
            }
        }
    }
    return Profit;
}

//+------------------------------------------------------------------+
//| Get last closed position type                                    |
//+------------------------------------------------------------------+
// Last closed order type check
int LastType()
{
    int type=-1;
    datetime dt=0;
    for(int i=OrdersHistoryTotal()-1;i>=0;i--)
    {
        if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
        {
            Print("OrderSelect in LastType failed. Error code: ", GetLastError());
            continue;
        }
        
        if(Symbol()==OrderSymbol() && OrderMagicNumber()==Magic) 
        {
            if(OrderCloseTime()>dt)
            {
                dt=OrderCloseTime();
                type=OrderType();
            }
        }
    }
    return(type);
}

//+------------------------------------------------------------------+
//| Create and manage chart objects for information display panel    |
//+------------------------------------------------------------------+
void CSSComent() 
{
    // Skip object creation in non-visual backtesting mode
    if (IsTesting() && !IsVisualMode()) return;
    int baseY = 60; 
    //-- Main background panel ----------------------------------------
    if (ObjectFind("BG") < 0) 
    {
        ObjectCreate("BG", OBJ_LABEL, 0, 0, 0);               // Create label object
        ObjectSetText("BG", "g", 180, "Webdings", Maroon);    // Webdings 'g' character creates rectangular background
        ObjectSet("BG", OBJPROP_CORNER, 0);                   // Anchor position: 0=Top-left
        ObjectSet("BG", OBJPROP_BACK, FALSE);                   // Render behind price chart
        ObjectSet("BG", OBJPROP_XDISTANCE, 0);                // Horizontal offset (pixels)
        ObjectSet("BG", OBJPROP_YDISTANCE, 15);               // Vertical offset (pixels)
    }

    //-- Top decorative line 1 ----------------------------------------
    if (ObjectFind("BG1") < 0) 
    {
        ObjectCreate("BG1", OBJ_LABEL, 0, 0, 0);
        ObjectSetText("BG1", "g", 180, "Webdings", DimGray);  // Gray separator line
        ObjectSet("BG1", OBJPROP_BACK, FALSE);                // Render in foreground
        ObjectSet("BG1", OBJPROP_XDISTANCE, 0);
        ObjectSet("BG1", OBJPROP_YDISTANCE, 42);              // Position below header
    }


    //-- Top decorative line 2 ----------------------------------------
    if (ObjectFind("BG2") < 0) 
    {
        ObjectCreate("BG2", OBJ_LABEL, 0, 0, 0);
        ObjectSetText("BG2", "g", 180, "Webdings", DimGray);
        ObjectSet("BG2", OBJPROP_CORNER, 0);
        ObjectSet("BG2", OBJPROP_BACK, FALSE);                 
        ObjectSet("BG2", OBJPROP_XDISTANCE, 0);
        ObjectSet("BG2", OBJPROP_YDISTANCE, 70);
    }


    //-- Panel title text ---------------------------------------------
    if (ObjectFind("NAME") < 0) 
    {
        ObjectCreate("NAME", OBJ_LABEL, 0, 0, 0);
        ObjectSetText("NAME", "FZ Scalper", 9, "Arial Bold", White); // Preserved original Russian text
        ObjectSet("NAME", OBJPROP_CORNER, 0);
        ObjectSet("NAME", OBJPROP_BACK, FALSE);                // Text in foreground
        ObjectSet("NAME", OBJPROP_XDISTANCE, 5);               // Horizontal adjustment
        ObjectSet("NAME", OBJPROP_YDISTANCE, 23);              // Vertical alignment
    }

    //-- Data section background 1 ------------------------------------
    if (ObjectFind("BG3") < 0) 
    {
        ObjectCreate("BG3", OBJ_LABEL, 0, 0, 0);
        ObjectSetText("BG3", "g", 110, "Webdings", DimGray);  // Smaller background element
        ObjectSet("BG3", OBJPROP_CORNER, 0);
        ObjectSet("BG3", OBJPROP_BACK, FALSE);
        ObjectSet("BG3", OBJPROP_XDISTANCE, 0);
        ObjectSet("BG3", OBJPROP_YDISTANCE, 73);              // Data section positioning
    } 


    //-- Data section background 2 ------------------------------------
    if (ObjectFind("BG5") < 0) 
    {
        ObjectCreate("BG5", OBJ_LABEL, 0, 0, 0);
        ObjectSetText("BG5", "g", 150, "Webdings", DimGray);
        ObjectSet("BG5", OBJPROP_CORNER, 0);
        ObjectSet("BG5", OBJPROP_BACK, FALSE);                // Foreground decoration
        ObjectSet("BG5", OBJPROP_XDISTANCE, 0);
        ObjectSet("BG5", OBJPROP_YDISTANCE,73);
    }
    
    // Refresh displayed content
    Coment();
}

//+------------------------------------------------------------------+
//| Update information panel content                                |
//+------------------------------------------------------------------+
void Coment() 
{
    string hedgeStatus = HedgeActive ? "Triggered" : "Not Triggered";
    
    Comment("" 
        + "\n" 
        + "\n"
        + "\n" 
        + "Account Information"  // Original Russian text preserved
        + "\n" 
        + "_______________________________________" 
        + "\n"  
        + "Stop Level:        "   + MarketInfo(Symbol(),MODE_STOPLEVEL)
        + "\n" 
        + "Spread:            "   + (Ask-Bid)/Point
        + "\n" 
        + "Balance:           " + DoubleToStr(AccountBalance(), 2) 
        + "\n" 
        + "Equity:            " + DoubleToStr(AccountEquity(), 2) 
        + "\n"  
        + "_______________________________________" 
        + "\n" 
        + "\n" 
        + "Trading Performance" 
        + "\n" 
        + "_______________________________________" 
        + "\n"
        + "Current Profit:    " + DoubleToStr(Profit(-1), 2)  
        + "\n"
        + "Buy Orders:        " + Count(OP_BUY) + "/" + 启动对冲单数  
        + "\n"
        + "Sell Orders:       " + Count(OP_SELL) + "/" + 启动对冲单数  
        + "\n"
        + "Hedge Status:      " + hedgeStatus                          
        + "\n"
        + "_______________________________________"  
        + "\n"
        + "Today's Profit:    " + DoubleToStr(ProfitDey(-1), 2) 
        + "\n"
        + "Yesterday's Profit: " + DoubleToStr(ProfitTuDey(-1), 2) 
        + "\n"
        + "Weekly Profit:     " + DoubleToStr(ProfitWeek(-1), 2) 
        + "\n"
        + "Monthly Profit:    " + DoubleToStr(ProfitMontag(-1), 2) 
        + "\n"
        + "All-Time Profit:   " + DoubleToStr(ProfitAllTime(-1), 2)   
    );
}
//+------------------------------------------------------------------+
//| Expert deinitialization function                                |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // Clean up all graphical objects
    ObjectsDeleteAll(0, "BG");
    ObjectsDeleteAll(0, "BG1");
    ObjectsDeleteAll(0, "BG2");
    ObjectsDeleteAll(0, "BG3");
    ObjectsDeleteAll(0, "BG5");
    ObjectsDeleteAll(0, "NAME");
    ObjectDelete(CLOSE_BUY_BUTTON);
    ObjectDelete(CLOSE_SELL_BUTTON);
}